import axios from "axios"
import router from "../../router"
import { PRO_BASE_URL, DEV_BASE_URL } from './config'
import { ElMessage } from 'element-plus'
import { userLogout } from '@/assets/common/utils'

const pagePath = window.location.host;
// console.log('当前页面路径request:', pagePath);
const isPro = Object.is(process.env.NODE_ENV, "production") // 判断开发环境，true为生产环境即线上，false为开发环境
// const baseURL = isPro ? PRO_BASE_URL : DEV_BASE_URL
const baseURL = isPro ? "https://"+pagePath+'/api/v1/' : 'v1/'

// 使用自定义的配置文件发送请求
const instance = axios.create({
    baseURL: baseURL,
    timeout: 200000,
})


// http 请求拦截器
instance.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem("token")
        if (token) {
            config.headers["Authorization"] = token
        }
        // get请求参数处理 空串置为null
        if (config.method === "get") {
            for (const key in config.params) {
                const value = config.params[key]
                if (typeof value === "string" && value.trim().length === 0) {
                    config.params[key] = null
                }
            }
        }
        return config
    },
    (err) => {
        return Promise.reject(err)
    }
)

// http 响应拦截器
instance.interceptors.response.use(
    (response) => {
        const token = response.headers.authorization || response.headers.Authorization
        if (token) {
            localStorage.setItem("token", token)
        }

        switch (response.data.code) {
            case 401:
            case 403:
                ElMessage({
                    message: "登录失效，请重新登录！",
                    type: "error",
                    duration: 2000,
                    grouping: true,
                })
                userLogout()
                router.replace("/")
                break
            case 407:
                ElMessage({
                    message: '暂无权限',
                    type: "error",
                    duration: 1500,
                    grouping: true,
                })
                break
            // case 500:
            //     ElMessage({
            //         message: response.data.code + "：" + response.data.msg,
            //         type: "error",
            //         duration: 1500,
            //     })
            //     break
        }
        return response

    },
    (error) => {
        if (error.response) {
            switch (error.response.status) {
                case 500:
                    ElMessage({
                        message: error.response.status + "：" + error.response.data.message,
                        type: "error",
                        duration: 1500,
                    })
                    break

            }
        }
        return Promise.reject(error)
    }
)

export default instance
